<template>
  <div class="room-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>房型管理</span>
          <el-button type="primary" @click="handleAdd">新增房型</el-button>
        </div>
      </template>

      <!-- 房型列表 -->
      <el-table :data="roomList" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="房型名称" />
        <el-table-column prop="price" label="价格">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容纳人数" />
        <el-table-column prop="area" label="房间面积">
          <template #default="scope"> {{ scope.row.area }}㎡ </template>
        </el-table-column>
        <el-table-column prop="stock" label="可用房间数" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === "active" ? "在售" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              link
              @click="handleToggleStatus(scope.row)"
              >{{ scope.row.status === "active" ? "下架" : "上架" }}</el-button
            >
            <el-button type="danger" link @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑房型' : '新增房型'"
        width="600px"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="房型名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入房型名称" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number
              v-model="formData.price"
              :min="0"
              :precision="2"
              :step="10"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="容纳人数" prop="capacity">
            <el-input-number
              v-model="formData.capacity"
              :min="1"
              :max="10"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="房间面积" prop="area">
            <el-input-number
              v-model="formData.area"
              :min="0"
              :precision="1"
              :step="5"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="可用房间数" prop="stock">
            <el-input-number
              v-model="formData.stock"
              :min="0"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="房间设施" prop="facilities">
            <el-checkbox-group v-model="formData.facilities">
              <el-checkbox label="tv">电视</el-checkbox>
              <el-checkbox label="wifi">WiFi</el-checkbox>
              <el-checkbox label="bathroom">独立卫浴</el-checkbox>
              <el-checkbox label="aircon">空调</el-checkbox>
              <el-checkbox label="window">窗户</el-checkbox>
              <el-checkbox label="minibar">迷你吧</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="房型图片" prop="images">
            <el-upload
              class="upload-demo"
              action="/api/upload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :before-upload="beforeUpload"
              multiple
              list-type="picture-card"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="房型描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              rows="4"
              placeholder="请输入房型描述"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

const route = useRoute();
const hotelId = route.params.id;

// 列表数据
const loading = ref(false);
const roomList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const formRef = ref(null);
const isEdit = ref(false);
const formData = reactive({
  name: "",
  price: 0,
  capacity: 1,
  area: 0,
  stock: 0,
  facilities: [],
  images: [],
  description: "",
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入房型名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  capacity: [{ required: true, message: "请输入容纳人数", trigger: "blur" }],
  area: [{ required: true, message: "请输入房间面积", trigger: "blur" }],
  stock: [{ required: true, message: "请输入可用房间数", trigger: "blur" }],
};

// 获取房型列表
const fetchRoomList = async () => {
  loading.value = true;
  try {
    // TODO: 调用获取房型列表API
    // const res = await getRoomList(hotelId, {
    //   page: currentPage.value,
    //   pageSize: pageSize.value
    // })
    // roomList.value = res.data.list
    // total.value = res.data.total
  } catch (error) {
    console.error("获取房型列表失败：", error);
    ElMessage.error("获取房型列表失败");
  } finally {
    loading.value = false;
  }
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchRoomList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchRoomList();
};

// 新增房型
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(formData, {
    name: "",
    price: 0,
    capacity: 1,
    area: 0,
    stock: 0,
    facilities: [],
    images: [],
    description: "",
  });
  dialogVisible.value = true;
};

// 编辑房型
const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    // TODO: 调用切换状态API
    // await toggleRoomStatus(row.id)
    ElMessage.success("操作成功");
    fetchRoomList();
  } catch (error) {
    console.error("操作失败：", error);
    ElMessage.error("操作失败");
  }
};

// 删除房型
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该房型吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      // TODO: 调用删除API
      // await deleteRoom(row.id)
      ElMessage.success("删除成功");
      fetchRoomList();
    } catch (error) {
      console.error("删除失败：", error);
      ElMessage.error("删除失败");
    }
  });
};

// 上传相关方法
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

const handleUploadSuccess = (res) => {
  formData.images.push(res.url);
};

const handleUploadError = () => {
  ElMessage.error("上传失败");
};

// 表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // TODO: 调用保存API
        // if (isEdit.value) {
        //   await updateRoom(formData.id, formData)
        // } else {
        //   await createRoom({ ...formData, hotelId })
        // }
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        fetchRoomList();
      } catch (error) {
        console.error("保存失败：", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 初始化
fetchRoomList();
</script>

<style scoped>
.room-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
